﻿using System;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using NguyenHoa.Web.App_Code;
using NguyenHoa.Services;
using System.Data;
using System.Web;

namespace NguyenHoa.Web.Controls
{
  public partial class TopMenu : BaseControl
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack && !Page.IsCallback)
      {
        ShowMenu();
      }

      if (Page.IsPostBack)
      {
        if (Request["__EVENTTARGET"] == "FrontMainMenuChange")
        {
          string[] paras = Request["__EVENTARGUMENT"].Split('|');
          if (paras.Length >= 2)
          {
            SelectedSubMenuItem = string.Empty;
            Response.Redirect(paras[1]);
          }
        }
      }
    }

    protected void rptMenu_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
      if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType != ListItemType.AlternatingItem) return;
      HttpContext currentContext = HttpContext.Current;
      string path = Request.Url.AbsolutePath;
      if (currentContext != null && currentContext.Items.Contains("HttpContextRewriteURL") && currentContext.Items["HttpContextRewriteURL"] != null)
      {
        path = currentContext.Items["HttpContextRewriteURL"].ToString();
      }
      string currentPage = path.Substring(path.LastIndexOf('/') + 1);
      DataRowView element = (DataRowView)e.Item.DataItem;
      HtmlControl lnkMenuItem = e.Item.FindControl("lnkMenuItem") as HtmlControl;
      HtmlControl divMenuItem = e.Item.FindControl("divMenuItem") as HtmlControl;
      if (lnkMenuItem != null)
      {
        //if (!GlobalCache.Instance.RewriteOn)
        //{
        //  lnkMenuItem.Attributes["href"] = "~/Pages/" + lnkMenuItem.Attributes["href"];
        //}
        //else
        //{
        //  lnkMenuItem.Attributes["href"] = "~/" + lnkMenuItem.Attributes["href"];
        //}

        lnkMenuItem.Attributes.Add("onclick", string.Format("javascript:getCurrentMainElement('{0}','{1}')"
                                 , element["Id"] != null ? element["Id"].ToString() : string.Empty
                                 , element["Link"] != null ? element["Link"].ToString() : string.Empty));
        if (element["Pages"] != null && element["Pages"].ToString().Contains("," + currentPage))
        {
          if (divMenuItem != null) divMenuItem.Attributes["class"] = "menuItem-active";
          SelectedMenuItem = element["Id"].ToString();
          SelectedMenuItemTitle = element["Title"].ToString();
        }
      }
    }

    private void ShowMenu()
    {
      DataSet listMainMenu = new MainMenuService().GetMainMenuByLanguage(CurrentLanguage.Id, MenuTypes.FrontEnd, null);
      rptMenu.DataSource = listMainMenu;
      rptMenu.DataBind();
    }
  }
}